/*
 *	jquery-lazy.js
 */
if (window.jQuery === undefined) {
	throw new Error('Please load jquery.js before loading jquery-lazy.js')
}
(function(window, jQuery) {
	jQuery.extend({
		debounce: function(fn, delay) {
			// 防抖
			let handle;
			return function() {
				clearTimeout(handle);
				handle = setTimeout(() => {
					fn(...arguments);
				}, delay);
			}

		}
	})
	// 抽离 监听元素是否显示和隐藏效果 的逻辑为jQuery.visible
	// 达到可复用的效果，并增加了可扩展性
	jQuery.visible = function(showCallback, hideCallback) {
		let self;
		// 如果支持IntersectionObserver直接返回IntersectionObserver对象
		if (IntersectionObserver) {
			self = new IntersectionObserver(entries => {
				entries.forEach(item => {
					if (item.intersectionRatio > 0) {
						showCallback && showCallback(item.target)
					} else if (item.intersectionRatio <= 0) {
						hideCallback && hideCallback(item.target)
					}
				})
			})
			return self;
		}
		// 不支持IntersectionObserver的话，就监听window的scroll事件
		let list = {
				length: 0
			},
			handler = function() {
				let key, item, target,
					top = document.documentElement.scrollTop,
					bottom = document.documentElement.scrollTop + document.documentElement.clientHeight;

				for (key in list) {
					if (list.hasOwnProperty(key) && key !== 'length') {
						item = list[key];
						target = item.target;

						if (item.visible) {
							if (target.offsetTop > bottom || (target.offsetTop + target.offsetHeight) < top) {
								item.visible = false;
								hideCallback && hideCallback(item.target)
							}
						} else {
							if (target.offsetTop <= bottom && (target.offsetTop + target.offsetHeight) >= top) {
								item.visible = true;
								showCallback && showCallback(item.target);
							}
						}
					}
				}
			}
		self = {
			init: jQuery.debounce(handler, 500),
			observe: function(el) {
				let index = list.length;
				el.lazyImgIndex = index;
				item = {
					target: el,
					visible: false
				}
				list[index] = item;
				list.length++;
				self.init();
			},
			unobserve: function(el) {
				let index = el.lazyImgIndex;

				if (index === undefined) {
					return false;
				}
				setTimeout(() => {
					delete list[index];
					el.lazyImgIndex = undefined;
				}, 0)
			}
		}
		window.addEventListener('scroll', self.init)
		return self;
	}
	jQuery.fn.extend({
		lazyImg: function(callback) {
			let observer;
			let callbacks = function(target) {
				if (target.dataset.hasOwnProperty('lazySrc')) {
					target.src = target.dataset.lazySrc;
					delete target.dataset.lazySrc;
					observer.unobserve(target)

					target.onload = function() {
						callback(target)
					};
				}
			}
			observer = jQuery.visible(callbacks);
			console.log(observer);
			this.each(function(index, item) {
				observer.observe(item)
			})
		}
	})
})(window, window.jQuery)